package com.fzz.learnitservice.service.impl.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fzz.learnitservice.pojo.po.Word;
import com.fzz.learnitservice.service.IWordService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 数据丰富，通过爬虫技术
 */

@Slf4j
@Component
public class WordEnrichmentTask {

    @Resource
    private IWordService wordService;

    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(5, TimeUnit.SECONDS)
            .readTimeout(5, TimeUnit.SECONDS)
            .build();

    private static final ObjectMapper mapper = new ObjectMapper();

    @Resource
    private DataSource dataSource;

    private static final String API_URL = "https://dict.youdao.com/jsonapi?q=";

    /**
     * 方法 1：爬取单个单词的英/美音标
     */
    public Map<String, String> fetchPhonetics(String word) {
        Map<String, String> result = new HashMap<>();
        try {
            String api = API_URL + URLEncoder.encode(word, StandardCharsets.UTF_8);
            Request request = new Request.Builder()
                    .url(api)
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)")
                    .build();

            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful() || response.body() == null) {
                    log.warn("⚠️ [{}] 接口请求失败，code={}", word, response.code());
                    return result;
                }

                JsonNode root = mapper.readTree(response.body().string());
                JsonNode ecNode = root.path("ec").path("word");

                String uk = "";
                String us = "";

                // 安全获取音标
                if (ecNode.isArray() && ecNode.size() > 0 && ecNode.get(0) != null) {
                    JsonNode first = ecNode.get(0);
                    uk = getPhonetic(first, "ukphone", "uk");
                    us = getPhonetic(first, "usphone", "us");
                } else if (ecNode.isObject()) {
                    uk = getPhonetic(ecNode, "ukphone", "uk");
                    us = getPhonetic(ecNode, "usphone", "us");
                }

                result.put("phonetic_uk", uk);
                result.put("phonetic_us", us);

                log.info("✅ 爬取[{}]音标 UK: [{}], US: [{}]", word, uk, us);
                return result;

            }
        } catch (Exception e) {
            log.warn("⚠️ [{}] 爬取音标失败：{}", word, e.toString());
            return result;
        }
    }

    /**
     * 方法 2：批量更新数据库中音标为空的单词
     */
    // @Scheduled(cron = "0 0 3 * * ?") // 可开启定时任务
    public void enrichPhoneticsBatch() {
        log.info("🚀 开始批量补全音标...");

        // ✅ 改进后的查询逻辑：兼容 NULL 与 空字符串
        List<Word> targetsWords = wordService.list(
                new LambdaQueryWrapper<Word>()
                        .nested(w -> w.isNull(Word::getPhoneticUk).or().eq(Word::getPhoneticUk, ""))
                        .or(w -> w.isNull(Word::getPhoneticUs).or().eq(Word::getPhoneticUs, ""))
                        .last("LIMIT 100")
        );
        if(targetsWords.isEmpty()) {
            log.info("😴 没有需要更新的单词，任务结束。");
            return;
        }

        List<Word> updatedList = new ArrayList<>();
        for (Word targetsWord : targetsWords) {
            String word = targetsWord.getWord();
            Map<String, String> info = fetchPhonetics(word);

            if(info.isEmpty()) continue;

            // ✅ 更新字段
            targetsWord.setPhoneticUk(info.getOrDefault("phonetic_uk", ""));
            targetsWord.setPhoneticUs(info.getOrDefault("phonetic_us", ""));
            updatedList.add(targetsWord);

            log.info("🎧 单词[{}]音标更新成功：UK={} | US={}", word, targetsWord.getPhoneticUk(), targetsWord.getPhoneticUs());

            // 每次爬虫读取数据等待200毫秒
            try {
                Thread.sleep(200L);
            } catch (InterruptedException ignored) {}
        }

        // ✅ 批量更新（MP 自带 saveOrUpdateBatch）
        if(!updatedList.isEmpty()) {
            wordService.updateBatchById(updatedList, 50);
            log.info("✅ 批量更新完成，共 {} 条记录。", updatedList.size());
        } else {
            log.info("⚠️ 没有可更新的音标数据。");
        }

    }

    /**
     * 工具：安全提取音标
     */
    private String getPhonetic(JsonNode node, String... keys) {
        for (String key : keys) {
            String v = safeText(node, key);
            if (org.springframework.util.StringUtils.hasText(v)) {
                return v.replaceAll("[\\[\\]]", "").trim();
            }
        }
        return "";
    }

    /**
     * 工具：安全获取文本
     */
    private String safeText(JsonNode node, String field) {
        if (node == null || node.isMissingNode() || node.isNull()) return "";
        JsonNode v = node.get(field);
        return (v == null || v.isNull()) ? "" : v.asText("");
    }
}



